package com.xingfudazi.app.util;

import com.xingfudazi.acl.cache.CacheClient;
import com.xingfudazi.common.constant.Constants;
import com.xingfudazi.common.exception.ExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author YuJiaMing
 * date 2023年11月14日 09:40
 */
@Slf4j
@Component
public class LockUtil {

    private static CacheClient cacheClient;


    @Autowired
    public void setCacheClient(CacheClient cacheClient) {
        LockUtil.cacheClient = cacheClient;
    }


    public static void ideLock(String key, int expire) {
        boolean lock = cacheClient.lock(Constants.IDE_LOCK + key, expire);
        if (!lock) {
            log.error("接口被幂等");
            throw ExceptionEnum.INTERFACE_IDEMPOTENT.unwrap();
        }
    }

    public static void ideUnLock(String key) {
        key = Constants.LOCK_PREFIX + Constants.IDE_LOCK + key;
        cacheClient.delete(key);
    }

    public static void tradeLock(Long nid, int expire) {
        String key = Constants.TRADE_LOCK + nid;
        log.error("交易加锁 key = {}", key);
        boolean lock = cacheClient.lock(key, expire);
        if (!lock) {
            log.error("交易执行中，同账号存在并发交易、或交未结束 key={}", key);
            throw ExceptionEnum.TRADE_RUNNING_LOCK.unwrap();
        }
    }

    public static void tradeEnd(Long nid) {
        String key = Constants.LOCK_PREFIX + Constants.TRADE_LOCK + nid;
        log.error("交易锁释放 key = {}", key);
        cacheClient.delete(key);
    }


}
